package com.homedo.microservice.distributed.id.service.task;

import com.homedo.common.util.Detect;
import com.homedo.microservice.distributed.id.service.bean.po.LeafAllocExtraNo;
import com.homedo.microservice.distributed.id.service.conf.LeafAllocExtraNoConf;
import com.homedo.microservice.distributed.id.service.persistence.dao.LeafAllocExtraNoDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
public class LeafAllocExtraNoConfUpdateTask {

    @Autowired
    private LeafAllocExtraNoDao leafAllocExtraNoDao;


    private static final Logger LOGGER = LoggerFactory.getLogger(LeafAllocExtraNoConfUpdateTask.class);

    @Scheduled(cron = "0/6 * * * * ?")
    public void update() {
        this.doSchedule();
    }

    private void doSchedule() {
        List<LeafAllocExtraNo> leafAllocExtraNos = leafAllocExtraNoDao.getAll();
        Map<Integer, LeafAllocExtraNo> confs = LeafAllocExtraNoConf.getInstance().getConfs();

        if (!Detect.notEmpty(leafAllocExtraNos)) {
            confs.clear();
            return;
        }

        leafAllocExtraNos.forEach(e -> {
            if (!confs.containsKey(e.getBizCode())) {
                confs.put(e.getBizCode(), e);
            } else {
                if (e != confs.get(e.getBizCode())) {
                    confs.put(e.getBizCode(), e);
                }
            }
        });

        confs.entrySet().forEach(e -> {
            boolean exist = this.exist(e.getKey(), leafAllocExtraNos);
            if (!exist) {
                confs.remove(e.getKey());
            }
        });
    }

    private boolean exist(Integer key, List<LeafAllocExtraNo> leafAllocExtraNos) {
        for (LeafAllocExtraNo leafAllocExtraNo : leafAllocExtraNos) {
            if (leafAllocExtraNo.getBizCode().equals(key)) {
                return true;
            }
        }
        return false;
    }

}
